package com.csw.shuanfa.CodeImprove.redlockThread.redLockHand;

import com.csw.shuanfa.GlobalConfig.exception.BusinessException;
import com.csw.shuanfa.GlobalConfig.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.Timer;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("lock")
@Slf4j
public class RedisLockTestController {
    @Autowired
    private RedisLock redisLock;

    private static String LOCK_KEY = "myLock";

    /**
     * http://localhost:8080/lock/testLock
     * http://localhost:8080/lock/testLock
     *
     * @throws InterruptedException
     */
    @RequestMapping("testLock")
    public Result testLock() throws InterruptedException {
        String lockValue = UUID.randomUUID().toString();
        //LOCK_KEY = LOCK_KEY + lockValue;

        // 尝试获取锁，最多等待10秒，锁自动释放时间为10秒
        boolean locked = redisLock.tryAcquireLock(LOCK_KEY, lockValue, 10);
        if (locked == false) {
            throw new BusinessException("获取锁失败");
        }
        Timer timer = redisLock.getTimer(LOCK_KEY);


        try {

            TimeUnit.SECONDS.sleep(60);
            //业务代码

        } finally {
            redisLock.releaseLock(LOCK_KEY, lockValue);
            timer.cancel();
            log.info("执行成功！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！{}" + new Date().toString() + LOCK_KEY);
        }
        return Result.ok();
    }


}
